//
//  AppDelegate.m
//  HappilyLoan
//
//  Created by zainishenbian on 2017/3/16.
//  Copyright © 2017年 zongqingxiangqian. All rights reserved.
//

#import "AppDelegate.h"
#import "AppDelegate+RootViewController.h"
#import "OpenUDID.h"
#import "ZFHeader.h"
#import "AppDelegate+AppBasicIformation.h"
#import "ZFIDVF.h"
/****************友盟统计******************/
#import "UMMobClick/MobClick.h"

/****************高德地图******************/
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapLocationKit/AMapLocationKit.h>
/****************极光推送******************/
#import "JPUSHService.h"
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
#import <AdSupport/AdSupport.h>
@import CoreLocation;
@import MapKit;

@interface AppDelegate ()<AMapLocationManagerDelegate,JPUSHRegisterDelegate> //协议
//@property(nonatomic) CLLocationManager *locationManager;
@property (nonatomic,strong)AMapLocationManager * locationManager;
@property(nonatomic,strong)NSString *locationStr;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//友盟
    [MobClick setLogEnabled:YES];
    UMConfigInstance.appKey = @"59018a8ab27b0a43ae0009e4";
    UMConfigInstance.secret = @"";
    UMConfigInstance.channelId = @"App Store";
    
    [MobClick startWithConfigure:UMConfigInstance];//配置以上参数后调用此方法初始化SDK
//推送
    //Required
    //notice：3.0.0及以后版本注册可以这样写，也可以继续用之前的注册方式
    NSString *advertisngId = [[[ASIdentifierManager sharedManager]advertisingIdentifier] UUIDString];
    JPUSHRegisterEntity *entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert |JPAuthorizationOptionBadge |JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue]>= 8.0) {
        // 可以添加 定义categories
        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    //如不需要使用IDFA，advertisingIdentifier 可为nil
    [JPUSHService  setupWithOption:launchOptions appKey:@"3f4888d24cc38e4c914a4530" channel:@"iOS-XYJD" apsForProduction:0 advertisingIdentifier:advertisngId];
    //2.1.9版本新增获取registration id block接口。
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if (resCode == 0) {
            NSLog(@"registrationID获取成功：%@",registrationID);
        }
        else{
            NSLog(@"registrationID获取失败，code：%d",resCode);
        }
    }];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkDidLogin:)name:kJPFNetworkDidLoginNotification object:nil];
    
//地图
    [AMapServices sharedServices].apiKey = @"5d52cc6d175cc2ca3580c0e63f78cc48";
    [[AMapServices sharedServices] setEnableHTTPS:YES];
    //设置状态栏字体颜色
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
    
    [UIApplication sharedApplication].idleTimerDisabled = TRUE;

//    
    //获取手机UDID
    NSString *UDID = [AppDelegate getIDFV];
    [[NSUserDefaults standardUserDefaults] setObject:UDID forKey:@"UDID"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    NSLog(@"%@",UDID);
    [self enterApp];
    [self configLocationManager];//创建地图manager
    
    return YES;
}
#pragma mark ———— 获取手机唯一标识
+ (NSString *)getIDFV
{
    NSString *IDFV = (NSString *)[ZFIDVF load:@"IDFV"];
    
    if ([IDFV isEqualToString:@""] || !IDFV) {
        
        IDFV = [UIDevice currentDevice].identifierForVendor.UUIDString;
        [ZFIDVF save:@"IDFV" data:IDFV];
    }
    
    return IDFV;
}

#pragma mark -- CLLocationManagerDelegate
- (void)configLocationManager
{
    self.locationManager = [[AMapLocationManager alloc] init];//实例化位置管理器
    [self.locationManager setDelegate:self];
    [self.locationManager startUpdatingLocation];//启动定位
    [self.locationManager setPausesLocationUpdatesAutomatically:NO];
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];//定位精度
    self.locationManager.locatingWithReGeocode = YES;//连续定位是否返回逆地理信息，默认NO。
//    [self.locationManager setAllowsBackgroundLocationUpdates:YES];
}
#pragma mark - AMapLocationManager Delegate
- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location reGeocode:(AMapLocationReGeocode *)reGeocode
{
    NSLog(@"location:{lat:%f; lon:%f; accuracy:%f}", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy);
        static BOOL isLocation = NO;
    if (reGeocode != nil && isLocation == NO) {
        NSString * provnice = reGeocode.province;
        NSString * city = reGeocode.city;
        NSString * district = reGeocode.district;
        NSString *codeStr = reGeocode.adcode;
        _locationStr = [NSString stringWithFormat:@"%@-%@-%@",provnice,city,district];
        //存入沙盒
        [[NSUserDefaults standardUserDefaults]setObject:_locationStr forKey:@"toLocationString"];
        [[NSUserDefaults standardUserDefaults]setObject:codeStr forKey:@"adcodeString"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        isLocation = YES;
        [self uploadOpenAppApiMessage:_locationStr];
    }
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
}
//实现注册APNs失败接口（可选）
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    NSLog(@"didReceiveRemoteNotification :%@", userInfo);
    [JPUSHService handleRemoteNotification:userInfo];
}
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:
(void (^)(UIBackgroundFetchResult))completionHandler
{
    NSLog(@"didReceiveRemoteNotification fetchCompletionHandler:%@", userInfo);
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}
//#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#pragma mark- JPUSHRegisterDelegate
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    NSDictionary * userInfo = notification.request.content.userInfo;
    
    UNNotificationRequest *request = notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容
    
    NSNumber *badge = content.badge;  // 推送消息的角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title = content.title;  // 推送消息的标题
    
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        //        NSLog(@"iOS10 前台收到远程通知:%@", [self logDic:userInfo]);
        //        [rootViewController addNotificationCount];
    }
    else {
        // 判断为本地通知
        NSLog(@"iOS10 前台收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,badge,sound,userInfo);
    }
    completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以设置
}
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    UNNotificationRequest *request = response.notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容
    
    NSNumber *badge = content.badge;  // 推送消息的角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title = content.title;  // 推送消息的标题
    
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        //        NSLog(@"iOS10 收到远程通知:%@", [self logDic:userInfo]);
        //        [rootViewController addNotificationCount];
    }
    else {
        // 判断为本地通知
        NSLog(@"iOS10 收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,badge,sound,userInfo);
    }
    
    completionHandler();  // 系统要求执行这个方法
}

/**
 *  登录成功，设置别名，移除监听
 *
 *  @param notification <#notification description#>
 */
- (void)networkDidLogin:(NSNotification *)notification {
    NSLog(@"已登录%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"phone"]);
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"phone"]) {
        NSString *phone = [[NSUserDefaults standardUserDefaults] objectForKey:@"phone"];
        [JPUSHService setAlias:phone callbackSelector:nil object:nil];
    }
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kJPFNetworkDidLoginNotification object:nil];
}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
